package br.edu.ufc.deti.connection;
import com.jcraft.jsch.*;

public class SFTPConnection {
	
	private String user;
	private String pass;
	private String IPServer;
	private String nomeDoArquivo;
	private String pathCopy;

	public SFTPConnection(String user, String pass, String IPServer, String nomeDoArquivo, String pathCopy){
		this.user = user;
		this.pass = pass;
		this.IPServer = IPServer;
		this.nomeDoArquivo = nomeDoArquivo;
		this.pathCopy = pathCopy;
	} 

	public int CopyFileServer2Client() {
        int retorno = 0;
		JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession(user, IPServer, 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(pass);
            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.get(nomeDoArquivo, pathCopy+nomeDoArquivo);
            sftpChannel.exit();
            session.disconnect();
            retorno = 1;
        } catch (JSchException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return retorno;
	}
	
    public static void main(String args[]) {
        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession("rafael", "200.19.191.110", 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword("1566rafael");
            System.out.println("conectando ssh");
            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            System.out.println("conectando sftp");
            ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.get("helloMPI-teste.txt", "helloMPI-teste.txt");
            System.out.println("copiando arquivos");
            sftpChannel.exit();
            session.disconnect();
            System.out.println("disconectando");
        } catch (JSchException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (SftpException e) {
            e.printStackTrace();
        }
        
        /* Exemplos de uso:
         * 
         * 		

	        SFTPConnection sftp = new SFTPConnection(userDestino, pass, hostDestino, nomeAplicacao+"_resultado.txt",
														pathServer+"/aplicacoes/");
			SFTPConnection sftp2 = new SFTPConnection(userDestino, pass, hostDestino, nomeAplicacao+"_resultado.txt",
					pathServer+"/WebContent/");
			sftp.CopyFileServer2Client();
			sftp2.CopyFileServer2Client();

         * 
         * 
         * */
        
        
        
    }
}
